// 仪表板JavaScript功能

let sentimentChart = null;
let sourceChart = null;
let emotionChart = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 设置默认日期
    const today = new Date();
    const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    document.getElementById('startDate').value = weekAgo.toISOString().split('T')[0];
    
    // 加载所有数据
    loadAllData();
});

// 加载所有数据
async function loadAllData() {
    try {
        await Promise.all([
            loadStatistics(),
            loadSentimentTrend(),
            loadSourceDistribution(),
            loadEmotionDistribution(),
            loadDataTable()
        ]);
    } catch (error) {
        console.error('加载数据失败:', error);
    }
}

// 加载统计信息
async function loadStatistics() {
    try {
        const response = await axios.get('/api/report');
        const data = response.data;
        
        document.getElementById('totalTexts').textContent = data.total_texts;
        document.getElementById('avgSentiment').textContent = data.avg_sentiment;
        document.getElementById('positiveRate').textContent = 
            Math.round((data.sentiment_distribution.positive / data.total_texts) * 100) + '%';
        document.getElementById('dataSources').textContent = Object.keys(data.sources).length;
    } catch (error) {
        console.error('加载统计信息失败:', error);
    }
}

// 加载情感趋势
async function loadSentimentTrend() {
    try {
        const response = await axios.get('/api/sentiment-trend');
        const data = response.data;
        
        const ctx = document.getElementById('sentimentChart').getContext('2d');
        
        if (sentimentChart) {
            sentimentChart.destroy();
        }
        
        sentimentChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(d => d.date),
                datasets: [{
                    label: '情感分数',
                    data: data.map(d => d.sentiment),
                    borderColor: 'rgb(75, 192, 192)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    tension: 0.1,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '每日情感趋势'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 1,
                        title: {
                            display: true,
                            text: '情感分数'
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('加载情感趋势失败:', error);
    }
}

// 加载数据来源分布
async function loadSourceDistribution() {
    try {
        const response = await axios.get('/api/sources');
        const data = response.data;
        
        const ctx = document.getElementById('sourceChart').getContext('2d');
        
        if (sourceChart) {
            sourceChart.destroy();
        }
        
        sourceChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: Object.keys(data),
                datasets: [{
                    data: Object.values(data),
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.8)',
                        'rgba(54, 162, 235, 0.8)',
                        'rgba(255, 205, 86, 0.8)',
                        'rgba(75, 192, 192, 0.8)',
                        'rgba(153, 102, 255, 0.8)'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    } catch (error) {
        console.error('加载数据来源分布失败:', error);
    }
}

// 加载情感分布
async function loadEmotionDistribution() {
    try {
        const response = await axios.get('/api/report');
        const data = response.data.sentiment_distribution;
        
        const ctx = document.getElementById('emotionChart').getContext('2d');
        
        if (emotionChart) {
            emotionChart.destroy();
        }
        
        emotionChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['正面', '中性', '负面'],
                datasets: [{
                    label: '文本数量',
                    data: [data.positive, data.neutral, data.negative],
                    backgroundColor: [
                        'rgba(75, 192, 192, 0.8)',
                        'rgba(255, 205, 86, 0.8)',
                        'rgba(255, 99, 132, 0.8)'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '情感分布'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '文本数量'
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('加载情感分布失败:', error);
    }
}

// 加载数据表格
async function loadDataTable() {
    try {
        const params = getFilterParams();
        const response = await axios.get('/api/data', { params });
        const data = response.data;
        
        const tbody = document.getElementById('dataTableBody');
        tbody.innerHTML = '';
        
        data.forEach(item => {
            const row = tbody.insertRow();
            row.innerHTML = `
                <td>${item.id}</td>
                <td>${item.text}</td>
                <td>${item.date}</td>
                <td><span class="badge bg-secondary">${item.source}</span></td>
                <td>
                    <span class="badge ${getSentimentBadgeClass(item.sentiment)}">
                        ${item.sentiment}
                    </span>
                </td>
            `;
        });
    } catch (error) {
        console.error('加载数据表格失败:', error);
    }
}

// 获取筛选参数
function getFilterParams() {
    return {
        start_date: document.getElementById('startDate').value,
        end_date: document.getElementById('endDate').value,
        source: document.getElementById('sourceFilter').value,
        keyword: document.getElementById('keywordFilter').value
    };
}

// 应用筛选
function applyFilters() {
    loadAllData();
}

// 重置筛选
function resetFilters() {
    const today = new Date();
    const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    document.getElementById('startDate').value = weekAgo.toISOString().split('T')[0];
    document.getElementById('sourceFilter').value = 'all';
    document.getElementById('keywordFilter').value = '';
    
    loadAllData();
}

// 获取情感标签样式
function getSentimentBadgeClass(sentiment) {
    if (sentiment > 0.6) return 'bg-success';
    if (sentiment < 0.4) return 'bg-danger';
    return 'bg-warning';
}

// 导出报告
async function exportReport() {
    try {
        const button = event.target;
        button.disabled = true;
        button.innerHTML = '<span class="loading"></span> 生成中...';
        
        const response = await axios.get('/api/report');
        const data = response.data;
        
        // 创建详细的PDF报告内容
        const reportContent = `
新疆维吾尔自治区博物馆网络文本分析报告
=====================================

生成时间：${data.generated_at}

一、数据概览
-----------
总文本数：${data.total_texts}
平均情感分数：${data.avg_sentiment}
分析时间范围：${document.getElementById('startDate').value} 至 ${document.getElementById('endDate').value}

二、情感分析结果
---------------
正面评价：${data.sentiment_distribution.positive}条 (${Math.round((data.sentiment_distribution.positive / data.total_texts) * 100)}%)
中性评价：${data.sentiment_distribution.neutral}条 (${Math.round((data.sentiment_distribution.neutral / data.total_texts) * 100)}%)
负面评价：${data.sentiment_distribution.negative}条 (${Math.round((data.sentiment_distribution.negative / data.total_texts) * 100)}%)

三、数据来源分布
---------------
${Object.entries(data.sources).map(([source, count]) => `${source}：${count}条`).join('\n')}

四、分析结论
-----------
基于当前数据分析，新疆维吾尔自治区博物馆在网络上的整体评价较为积极，
正面评价占比超过${Math.round((data.sentiment_distribution.positive / data.total_texts) * 100)}%。

报告生成完成。
        `;
        
        // 创建下载链接
        const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `新疆博物馆文本分析报告_${new Date().toISOString().split('T')[0]}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-download"></i> 导出报告';
        
    } catch (error) {
        console.error('导出报告失败:', error);
        alert('导出报告失败，请稍后重试');
    }
}

// 刷新词云
function refreshWordcloud() {
    const img = document.getElementById('wordcloudImage');
    img.src = '/api/wordcloud?' + new Date().getTime();
}
